<template>
  <el-form ref="ruleFormRef" style="max-width: 600px;margin: 200px auto;" :model="ruleForm" :rules="rules"
    label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
    <el-form-item label="用户名" prop="LoginName">
      <el-input v-model="ruleForm.LoginName" />
    </el-form-item>
    <el-form-item label="密码" prop="LoginPwd">
      <el-input v-model="ruleForm.LoginPwd" type="password" />
    </el-form-item>
    <el-form-item label=" " prop="name">
      <el-checkbox v-model="ruleForm.Remember" label="保持登录状态" size="large" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'

import { useRoute, useRouter } from 'vue-router'
import { loginUser } from '@/api/user'//登录方法
import { useStore } from '@/stores/userInfo'//pinia


const user = useStore();

const route = useRoute();
const router = useRouter();

//生命周期函数
onMounted(() => {
  if (localStorage.getItem("LoginName") != '') {
    ruleForm.LoginName = localStorage.getItem("name") ?? ""
    ruleForm.LoginPwd = localStorage.getItem("pwd") ?? ""

    ruleForm.Remember = true;
  }
})

interface RuleForm {
  LoginName: string
  LoginPwd: string
  Remember: boolean
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  LoginName: '',
  LoginPwd: '',
  Remember: false,
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
  LoginName: [
    { required: true, message: '邮箱或手机号不能为空', trigger: 'blur' }
  ],
  LoginPwd: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
  ],
})




const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))


//登录
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      //登录请求
      const res = await loginUser({
        LoginName: ruleForm.LoginName,
        LoginPwd: ruleForm.LoginPwd
      })

      console.log(res.data.data);

      //存储账号密码
      localStorage.setItem("name", ruleForm.LoginName);
      localStorage.setItem("pwd", ruleForm.LoginPwd);

      //获取 token 值 放到 pinia 里
      user.userinfo.usertoken = res.data.data.Token;
      user.userinfo.userName = res.data.data.LoginName;
      user.userinfo.userId = res.data.data.AccountId;

      ElMessage.success("登录成功")
      router.push("/index");

    } else {
      console.log('error submit!', fields)
    }
  })
}


//登录
const login = () => {
  async () => {
    const res = await loginUser({
      LoginName: ruleForm.LoginName,
      LoginPwd: ruleForm.LoginPwd
    })

    user.userinfo.usertoken = res.data.data.Token;
    user.userinfo.userName = res.data.data.LoginName;
    user.userinfo.userId = res.data.data.AccountId;

    ElMessage.success("登录成功")
    router.push("/index");
  }

}
</script>